package hanlen.mq.starter.configuration;

import hanlen.mq.starter.support.RedisQueueDlqSupport;
import hanlen.mq.starter.support.thread.AsyncThreadPoolChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

/**
 * archives-service
 *
 * @author MrYe
 * @Description
 * @date 2021-10-23 16:38
 */
@Slf4j
@EnableScheduling
public class RedisMonitorConfiguration implements SchedulingConfigurer, ApplicationContextAware {

    private ApplicationContext context;

    @Value("${hanlenmq.schedule.dlq.check.cron:0 0/10 * * * ?}")
    private String dlqCorn;

    /**
     * 检查异步线程池状态 每1分钟检测一次
     */
    @Value("${hanlenmq.schedule.thread.check.cron:0/60 * * * * ?}")
    private String threadCorn;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        final RedisQueueDlqSupport support = context.getBean(RedisQueueDlqSupport.class);
        taskRegistrar.addTriggerTask(support::monitor, triggerContext ->
            new CronTrigger(dlqCorn).nextExecutionTime(triggerContext)
        );
        final AsyncThreadPoolChecker threadPoolChecker = context.getBean(AsyncThreadPoolChecker.class);
        taskRegistrar.addTriggerTask(threadPoolChecker::monitor, triggerContext ->
            new CronTrigger(threadCorn).nextExecutionTime(triggerContext)
        );
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

}
